<template>
  <div class="waybill-box">
    <common-pull-down-up
      v-model:pullOptions="pullOptions"
      :pageOptions="queryParams"
      :title="'运单'"
      :whiteStyle="true"
      @loadData="loadData"
      @pullDownRefresh="pullDownRefresh"
    >
      <template #top>
        <div class="waybill-box__top">
          <form action="/" class="search__box">
            <van-search
              v-model="queryModel.searchVal"
              show-action
              placeholder="装卸货地址/运单号"
              @search="handleQueryData"
            >
              <template #left-icon>
                <img src="@/assets/image/waybill/search.png" alt="" class="magnifier" />
              </template>
              <template #action>
                <div @click="handleQueryData" class="search-btn">搜索</div>
              </template>
            </van-search>
          </form>
          <div class="tabs">
            <div class="tab">
              <div
                class="tab__item"
                :class="item.value === currentStatus ? 'tab__active' : ''"
                v-for="item in BillTabsEm"
                @click="onTabClick(item)"
                :key="item.value"
              >
                {{ item.description }}
              </div>
              <div class="clearfix"></div>
            </div>
          </div>
        </div>
      </template>
      <template #content>
        <waybill-item-component class="list__item" v-for="item in pullOptions.rows" :detail="item" :key="item.id" />
      </template>
      <template #noMore>
        <img src="@/assets/image/mine/complaint/no_more.png" />
      </template>
      <template #noMoreText>
        <span>暂无投诉</span>
      </template>
    </common-pull-down-up>
    <PhonePopup :isShow="isTelPhoneShow" :telNumber="mobile" @cancel_show="isTelPhoneShow = false" />
    <van-popup v-model:show="passwordPoppup" position="bottom">
      <div class="passwordPoppup">
        <div class="memo">请输入支付密码</div>
        <van-password-input :value="payPassword" :focused="true" />
        <van-number-keyboard
          v-model="payPassword"
          :show="true"
          @input="onCommit"
          maxlength="6"
          @blur="passwordPoppup = false"
        />
      </div>
    </van-popup>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref, toRefs } from 'vue'
import { useRouter } from 'vue-router'
import http from '@/http'
import store from '@/store'
import { api } from '@/http/api'
import { WAY_BILL_MAP_KEY } from '@/utils/constant'
import storage from 'good-storage'
import CommonPullDnUp from '@/components/CommonPullDnUp.vue'
import WaybillItem from './components/WayBillItem.vue'
import usePullDownUp from '@/utils/usePullDownUp'
import PhonePopup from '@/components/PhonePopup.vue'
import { Toast, Dialog } from 'vant'
import { BillTabsEm } from '@/store/enums'
import { changeDateType } from '../utils/common'
import {
  LoadReceiptStatusEm,
  UnloadReceiptStatusEm,
  LoadRejectStatusEm,
  UnloadRejectStatusEm,
  BillOpearStatusEm,
  PointTypeEm,
  PayStatusEm,
  BillOpeartionEm,
  BillAllStatusEm,
  DataTypeEm,
  CommentTypeEm
} from '../utils/enums'

export default defineComponent({
  name: 'WaybillNew',
  components: {
    'common-pull-down-up': CommonPullDnUp,
    'waybill-item-component': WaybillItem,
    PhonePopup
  },
  setup() {
    const currentStatus = ref(BillTabsEm.ALL.value) // 当前顶部导航栏状态

    const currentPhone = reactive<any>({
      mobile: '', // 手机号码
      isTelPhoneShow: false // 是否显示 联系电话模态框
    })

    const currentPay = reactive<any>({
      payPassword: '', // 支付密码
      passwordPoppup: false // 是否显示支付模态框
    })

    const currentDetail = ref<any>({}) // 当前选中项

    const queryModel = reactive({
      status: '', // 当前顶部导航栏状态  运单所需
      searchVal: '', // 模糊搜索
      orderStatus: '', // 当前导航栏状态 订单所需
      commentType: '' // 评价类型 运单所需
    })

    const router = useRouter()

    let requestUrl = ref('waybill/handleGetWaybillAllList') // 当前的url

    const { pullOptions, loadData, pullDownRefresh, queryParams, handleQueryData, onRefresh } = usePullDownUp<any>({
      url: requestUrl,
      queryModel,
      successBuildData: (rows: any) => {
        buildData(rows)
      }
    })

    const onTabClick = async (item: any): Promise<void> => {
      currentStatus.value = item.value
      if (currentStatus.value === BillTabsEm.ALL.value) {
        requestUrl.value = 'waybill/handleGetWaybillAllList'
      } else if (currentStatus.value === BillTabsEm.WAIT_RE.value) {
        requestUrl.value = 'waybill/handleGetOrderList'
        queryParams.orderStatus = BillTabsEm.WAIT_RE.value
        queryParams.status = ''
      } else {
        requestUrl.value = 'waybill/handleGetWaybillList'
        queryParams.status = currentStatus.value
        queryParams.orderStatus = ''
      }
      onRefresh()
    }

    // 支付
    const onCommit = async (value: any): Promise<void> => {
      const current = currentDetail.value
      if (String(currentPay.payPassword).length < 5) return
      const updateData: any = {
        billId: current.id, //	运单id		true
        password: currentPay.payPassword + value //	支付密码
      }

      if (current.payStatus === PayStatusEm.NO_RECEIPT_PAY.value) {
        // 回单付
        updateData.amount = current.receiptAmount || 0
        updateData.type = BillOpeartionEm.CALLBACK.value
      } else if (current.payStatus === PayStatusEm.NO_MONTH_PAY.value) {
        updateData.amount = current.settleAmount || 0
        updateData.type = BillOpeartionEm.MOUNTH.value
      }
      const result = await store.dispatch('waybill/handleTransportBillConfirmCons', updateData)
      if (result) {
        Toast.success('操作成功')
        handleQueryData()
        currentPay.passwordPoppup = false
        currentPay.payPassword = ''
      }
    }

    // 查看单据
    const onCheckBill = (
      item: any,
      billStatusType: number,
      type: '1' | '2' | string,
      showTab = 0,
      showOpeartion = 1
    ): void => {
      router.push({
        name: 'Receipt',
        query: {
          billId: item.id,
          billStatusType,
          showTab,
          type,
          showOpeartion,
          payStatus: item.payStatus
        }
      })
    }

    // 取消订单
    const handleCancelOrder = (id: string, callback?: any) => {
      Dialog.confirm({
        title: '',
        message: '您确认取消当前订单吗'
      })
        .then(() => {
          sureRequest()
        })
        .catch(() => {
          //
        })
      function sureRequest() {
        http<string>({
          url: api.updateCancelOrder,
          method: 'post',
          data: { id }
        }).then((res: any) => {
          if (callback && typeof callback === 'function') callback()
        })
      }
    }

    // 联系货主
    const goTelphone = (detail: any) => {
      if (!detail) return
      currentPhone.mobile = detail.driverMobile ? detail.driverMobile : detail.carrierMobile
      currentPhone.isTelPhoneShow = true
    }

    // 查看地图
    const handleEnterMap = (detail: any): void => {
      storage.session.set(WAY_BILL_MAP_KEY, detail)
      router.push({
        path: '/waybill/transport-map'
      })
    }

    //去评价
    const onGoEvaluate = (item: any) => {
      router.push({ name: 'Evaluate', params: { params: JSON.stringify(item) } })
    }

    // 待接单
    const waitingList = (detail: any): void => {
      //TODO 取货主发布订单的装货时间
      detail.billOrderTime = `装货时间: ${changeDateType(detail.shipTime, 'MMDD')}前`

      //TODO 当前状态
      detail.billOrderStatusName = '待接单'

      //TODO 操作按钮
      detail.operationBtns = [
        {
          title: '取消订单',
          class: 'default__btn',
          fn: () => {
            handleCancelOrder(detail.id, () => {
              handleQueryData()
            })
          }
        }
      ]
      if (detail.pointType === PointTypeEm.FIND.value) {
        //
      } else {
        // 派单 类型
        detail.operationBtns.push({
          title: `联系${detail.driverMobile ? '司机' : '承运商'}`,
          class: 'active__btn',
          fn: () => {
            goTelphone(detail)
          }
        })
      }
    }

    // 待装货
    const forTheLoading = (detail: any): void => {
      //TODO 取货主发布订单的装货时间
      detail.billOrderTime = `装货时间: ${changeDateType(detail.shipTime, 'MMDD')}前`
      detail.billOrderStatusName = '待装货'

      //TODO 操作按钮
      detail.operationBtns.push({
        title: '联系司机',

        class: 'default__btn',
        fn: () => {
          goTelphone(detail)
        }
      })

      if (
        detail.loadReceiptStatus === LoadReceiptStatusEm.ALREADY_UPLOAD.value &&
        detail.loadRejectStatus === LoadRejectStatusEm.NOT_REJECTED.value
      ) {
        // 已上传 并未驳回
        detail.billOrderSecStatusName = '待确认'
        detail.secStatusColor = '#FC9E29'

        // 操作按钮

        detail.operationBtns.push({
          title: '查看单据',
          class: 'active__btn',
          fn: () => {
            onCheckBill(detail, BillOpeartionEm.BILL.value, String(BillOpearStatusEm.SHIPMENT.value))
          }
        })
      } else if (
        detail.loadReceiptStatus === LoadReceiptStatusEm.ALREADY_UPLOAD.value &&
        detail.loadRejectStatus === LoadRejectStatusEm.REJECT.value
      ) {
        // 驳回
        detail.billOrderSecStatusName = '已驳回'
        detail.secStatusColor = '#FF6459'
        detail.operationBtns.push({
          title: '查看单据',
          class: 'active__btn',
          fn: () => {
            onCheckBill(detail, BillOpeartionEm.BILL.value, String(BillOpearStatusEm.SHIPMENT.value))
          }
        })
      }
    }

    // 运输中
    const inTransit = (detail: any): void => {
      //TODO 运输中状态取货主发布订单的卸货时间
      detail.billOrderTime = `卸货时间: ${changeDateType(detail.unloadTime, 'MMDD')}前`

      //TODO 当前状态
      detail.billOrderStatusName = '运输中'

      //TODO 操作按钮
      detail.operationBtns = [
        {
          title: '查看单据',
          class: 'default__btn',

          fn: () => {
            onCheckBill(detail, BillOpeartionEm.BILL.value, String(BillOpearStatusEm.SHIPMENT.value), 0, 0)
          }
        },
        {
          title: `查看轨迹`,
          class: 'active__btn',
          fn: () => {
            handleEnterMap(detail)
          }
        }
      ]
    }

    // 待签收
    const waitingSign = (detail: any): void => {
      //TODO 此处显示抵达时间（司机第一次上传卸货单据的时间）
      detail.billOrderTime = `抵达时间: ${changeDateType(detail.receiptTime, 'YYMMDD')}`
      detail.billOrderStatusName = '待签收'

      //TODO 操作按钮
      if (
        detail.unloadReceiptStatus === UnloadReceiptStatusEm.ALREADY_UPLOAD.value &&
        detail.unloadRejectStatus === UnloadRejectStatusEm.NOT_REJECTED.value
      ) {
        // 已上传卸货单据 并且未驳回

        detail.billOrderSecStatusName = '待确认'
        detail.secStatusColor = '#FC9E29'

        detail.operationBtns.push({
          title: `联系${detail.driverMobile ? '司机' : '承运商'}`,
          class: 'default__btn',
          fn: () => {
            goTelphone(detail)
          }
        })
        detail.operationBtns.push({
          title: `查看单据`,
          class: 'active__btn',
          fn: () => {
            onCheckBill(detail, BillOpeartionEm.SIGN.value, String(BillOpearStatusEm.UNLOADING.value))
          }
        })
      } else if (
        detail.unloadReceiptStatus === UnloadReceiptStatusEm.ALREADY_UPLOAD.value &&
        detail.unloadRejectStatus === UnloadRejectStatusEm.REJECT.value
      ) {
        // 已上传卸货单据 并且已驳回
        detail.billOrderSecStatusName = '已驳回'
        detail.secStatusColor = '#FF6459'
        detail.operationBtns.push({
          title: `联系${detail.driverMobile ? '司机' : '承运商'}`,
          class: 'active__btn',
          fn: () => {
            goTelphone(detail)
          }
        })
        detail.operationBtns.push({
          title: `查看单据`,
          class: 'active__btn',
          fn: () => {
            onCheckBill(detail, BillOpeartionEm.SIGN.value, String(BillOpearStatusEm.UNLOADING.value))
          }
        })
      }
    }

    // 待结算
    const waitingBilling = (detail: any): void => {
      //TODO 此处显示抵达时间（司机第一次上传卸货单据的时间）
      detail.billOrderTime = `抵达时间: ${changeDateType(detail.receiptTime, 'YYMMDD')}`
      //TODO 当前状态.
      detail.billOrderStatusName = '待结算'

      //TODO 操作按钮
      detail.operationBtns.push({
        title: `查看单据`,
        class: 'default__btn',
        fn: () => {
          onCheckBill(detail, BillOpeartionEm.SIGN.value, String(BillOpearStatusEm.SHIPMENT.value), 1, 0)
        }
      })

      if (detail.payStatus === PayStatusEm.NO_RECEIPT_PAY.value) {
        detail.billOrderSecStatusName = '未支付回单付'
        detail.secStatusColor = '#ff6459'
        // 未支付回单付
        detail.operationBtns.push({
          title: `回单支付`,
          class: 'active__btn',
          fn: () => {
            currentDetail.value = detail
            currentPay.passwordPoppup = true
          }
        })
      } else if (detail.payStatus === PayStatusEm.NO_MONTH_PAY.value) {
        detail.billOrderSecStatusName = '未支付月结'
        detail.secStatusColor = '#ff6459'
        detail.operationBtns.push({
          title: `月结支付`,
          class: 'active__btn',
          fn: () => {
            currentDetail.value = detail
            currentPay.passwordPoppup.value = true
          }
        })
      }
    }

    // 已完成
    const alreadyFinished = (detail: any): void => {
      // TODO 已完成状态此处显示付款时间（付款全部完成时间）
      detail.billOrderTime = `付款时间: ${changeDateType(detail.settleTime, 'YYMMDD')}`
      //TODO 操作按钮

      detail.operationBtns.push({
        title: `查看单据`,
        class: 'default__btn',
        fn: () => {
          onCheckBill(detail, BillOpeartionEm.SIGN.value, String(BillOpearStatusEm.SHIPMENT.value), 1, 0)
        }
      })

      if (detail.consToDriverStatus === 1) {
        detail.billOrderStatusName = '待评价'
        detail.operationBtns.push({
          title: `评价司机`,
          class: 'active__btn',
          fn: () => {
            onGoEvaluate(detail)
          }
        })
      } else if (detail.driverToConsStatus === CommentTypeEm.ALREADY_EVALUATED.value) {
        detail.billOrderStatusName = '已评价'
      } else {
        detail.billOrderStatusName = '已完成'
      }
    }

    // 已取消
    const alreadyCancel = (detail: any): void => {
      // TODO 已取消状态
      detail.billOrderTime = `取消时间: ${changeDateType(detail.updateTime, 'YYMMDD')}`

      // TODO 当前状态.
      detail.billOrderStatusName = '已取消'
    }

    // 已拒绝
    const alreadyReject = (detail: any) => {
      // TODO 已拒绝状态
      detail.billOrderTime = `拒绝时间: ${changeDateType(detail.updateTime, 'YYMMDD')}`

      // TODO 当前状态.
      detail.billOrderStatusName = '已拒绝'
    }

    // 重构订单数据
    const buildOrderData = (item: any, billCurrentObj: any): any => {
      item.dataType = Number(DataTypeEm.ORDER.value)
      item.billOrderStatus = item.orderStatus
      item.billOrderNo = '订单号: ' + item.orderNo
      return item
    }

    // 重构运单数据
    const buildTransData = (item: any, billCurrentObj: any): any => {
      item.dataType = DataTypeEm.TRANS.value
      if (billCurrentObj.value === item.status) {
        item.billOrderStatus = item.status
      }
      item.billOrderNo = '运单号: ' + item.billNo
    }

    // 重新构建数据
    const buildData = (list: any[]): any => {
      list.forEach(item => {
        item.operationBtns = [] // 创建空按钮数组
        for (let attr in BillAllStatusEm) {
          const billCurrentObj = BillAllStatusEm[attr]
          if (item.orderStatus) {
            // 订单
            if (billCurrentObj.value === item.orderStatus) {
              buildOrderData(item, billCurrentObj)
            }
          } else {
            buildTransData(item, billCurrentObj)
          }
        }
        if (item.billOrderStatus === BillAllStatusEm.WAIT_RE.value) {
          //TODO 待接单状态
          waitingList(item)
        } else if (item.billOrderStatus === BillAllStatusEm.FORWARDING.value) {
          //TODO 待装货状态
          forTheLoading(item)
        } else if (item.billOrderStatus === BillAllStatusEm.In_TRANSIT.value) {
          //TODO 运输中状态
          inTransit(item)
        } else if (item.billOrderStatus === BillAllStatusEm.TO_SIGNED.value) {
          //TODO 待签收状态
          waitingSign(item)
        } else if (item.billOrderStatus === BillAllStatusEm.SIGNED.value) {
          //TODO 待结算状态
          waitingBilling(item)
        } else if (item.billOrderStatus === BillAllStatusEm.FINISHED.value) {
          //TODO 已完成状态
          alreadyFinished(item)
        } else if (item.billOrderStatus === BillAllStatusEm.CANCELLED.value) {
          //TODO 已取消状态
          alreadyCancel(item)
        } else if (item.billOrderStatus === BillAllStatusEm.REJECT.value) {
          //TODO 已拒绝状态
          alreadyReject(item)
        }
      })
    }

    return {
      loadData,
      queryParams,
      pullDownRefresh,
      pullOptions,
      ...toRefs(currentPhone),
      ...toRefs(currentPay),
      onCommit,
      onTabClick,
      currentStatus,
      handleQueryData,
      queryModel,
      BillTabsEm
    }
  }
})
</script>
<style lang="scss">
.waybill-box {
  .commonPullDnUp__ct {
    padding-top: 0 !important;
  }
}
</style>
<style lang="scss" scoped>
@import '@/style/variables.scss';
@import '@/style/mixins.scss';
.waybill-box {
  width: 100%;
  height: 100%;

  &__top {
    width: 100%;
    padding: 30px 0px 0px 0px;
    box-sizing: border-box;
    .search__box {
      width: 100%;
    }
    .tabs {
      width: 100%;
      overflow: auto;
      -ms-overflow-style: none;
      overflow: -moz-scrollbars-none;
      box-sizing: border-box;
      padding: 20px 12px 0 12px;
      &::-webkit-scrollbar {
        width: 0 !important;
      }
      .clearfix {
        clear: both;
      }
      .tab {
        width: max-content;
        height: 30px;
      }
      .tab__item {
        line-height: 30px;
        width: 72px;
        text-align: center;
        float: left;
      }
      .tab__active {
        width: 72px;
        height: 30px;
        line-height: 30px;
        background: $color-primary;
        box-shadow: 0px 4px 16px 0px rgba(64, 158, 255, 0.14);
        border-radius: 15px;
        text-align: center;
        color: #fff;
      }
    }
  }

  .passwordPoppup {
    width: 100%;
    padding-top: 30px;
    height: 355px;

    .memo {
      text-align: center;
      font-size: 14px;
      margin-bottom: 10px;
      color: #333;
    }
  }
  form {
    background-color: #fff;
  }

  ::v-deep(.van-search__content) {
    border-radius: 10px;
    box-shadow: 0px 2px 14px 0px rgba(185, 185, 185, 0.1);
  }

  ::v-deep(.van-search .van-cell) {
    padding: 11px 0;
  }

  .search-btn {
    width: 50px;
    height: 46px;
    background-color: $color-primary;
    box-shadow: 0px 4px 16px 0px rgba(64, 158, 255, 0.3);
    border-radius: 12px;
    font-weight: 500;
    text-align: center;
    line-height: 46px;
    color: #fff;
  }

  .magnifier {
    vertical-align: middle;
    width: 20px;
    height: 20px;
    margin-right: 3px;
  }
}
</style>
